@ECHO OFF

REM 设置控制台代码页为UTF-8以支持中文显示
chcp 65001 >NUL

pushd %~dp0

REM Command file for Sphinx documentation
set CONFIG_FILE=..\build_path.cfg
REM 读取配置文件
if not exist "%CONFIG_FILE%" (
    echo 错误: 配置文件 %CONFIG_FILE% 不存在
    exit /b 1
)

set BUILD_PATH=
for /f "usebackq delims=" %%i in ("%CONFIG_FILE%") do set "BUILD_PATH=%%i"

REM 验证路径有效性
if "%BUILD_PATH%"=="" (
    echo 错误: 配置文件内容为空
    exit /b 1
)

if not exist "%BUILD_PATH%\" (
    echo 错误: 构建路径不存在: %BUILD_PATH%
    exit /b 1
)

if "%SPHINXBUILD%" == "" (
	set SPHINXBUILD=%BUILD_PATH%\Python\Scripts\sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
	echo.
	echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
	echo.installed, then set the SPHINXBUILD environment variable to point
	echo.to the full path of the 'sphinx-build' executable. Alternatively you
	echo.may add the Sphinx directory to PATH.
	echo.
	echo.If you don't have Sphinx installed, grab it from
	echo.https://www.sphinx-doc.org/
	exit /b 1
)

if "%1" == "clean-api" (
	echo.正在清理API文档...
	if exist %SOURCEDIR%\D5Core rmdir /s /q %SOURCEDIR%\D5Core
	if exist %SOURCEDIR%\_autosummary rmdir /s /q %SOURCEDIR%\_autosummary
	if exist %SOURCEDIR%\modules.rst del /q %SOURCEDIR%\modules.rst
	goto end
)

if "%1" == "apidoc" (
	echo.正在自动生成API文档...
	python custom_apidoc.py
	goto end
)

if "%1" == "html" (
	echo.正在生成HTML文档...
	call make.bat clean-api
	call make.bat apidoc
	%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
	goto end
)

if "%1" == "livehtml" (
	echo.正在启动实时文档预览...
	call make.bat clean-api
	call make.bat apidoc
	sphinx-autobuild %SOURCEDIR% %BUILDDIR%/html %SPHINXOPTS% %O%
	goto end
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
